package nc.bs.scm.sourcebill;

import java.io.PrintStream;
import java.lang.reflect.Method;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import nc.bs.ml.NCLangResOnserver;
import nc.bs.mm.pub.pub1050.SourceBillDMO;
import nc.bs.scm.inter.MMHelper;
import nc.bs.scm.mm.pub.pub1050.SourceBillBO;
import nc.bs.scm.pub.ScmPubImpl;
import nc.bs.sm.createcorp.CreatecorpDMO;
import nc.itf.pd.inner.IMMSourceBill;
import nc.itf.scm.sourcebill.ISourceBill;
import nc.itf.scm.sourcebill.ISourceBillFinder;
import nc.vo.pub.AggregatedValueObject;
import nc.vo.pub.BusinessException;
import nc.vo.scm.sourcebill.ConstantVO;
import nc.vo.scm.sourcebill.LightBillVO;
import nc.vo.scm.sourcebill.SourceBillParaV3;

// Referenced classes of package nc.bs.scm.sourcebill:
//            DefaultSourceDMO, DMMissionbillSourceDMO, DMDeliverPlanSourceDMO, DMDeliverbillSourceDMO, 
//            DMTransInfoSourceDMO, DMWayLostSourceDMO, DMDelivFeeBillSourceDMO, SettleBillSourceDMO, 
//            InvoiceSourceDMO, ICBillSourceDMO, MRBillSourceDMO

public class SourceBillImpl
    implements ISourceBill
{

    public SourceBillImpl()
    {
        m_bMMUsed = false;
    }

    public void findForwardBillsForBill(LightBillVO voBillInfo)
        throws BusinessException
    {
        LightBillVO voaCurrentResult[] = voBillInfo.getForwardBillVOs();
        if(voaCurrentResult != null && voBillInfo.getDepth() != null && voaCurrentResult.length == voBillInfo.getDepth().intValue())
        {
            System.out.println((new StringBuilder()).append("Hint:Depth is OK.").append(voBillInfo.getDepth().intValue()).toString());
            return;
        }
        System.out.println((new StringBuilder()).append("fwd=").append(voBillInfo.getType()).toString());
        searchForwardBills(voBillInfo);
        if(voBillInfo.getType().startsWith("A"))
        {
            findMMForwardBillsForBill(voBillInfo);
            return;
        }
        try
        {
            DefaultSourceDMO dmo = new DefaultSourceDMO();
            voBillInfo.setTypeName(NCLangResOnserver.getInstance().getStrByID("billtype", (new StringBuilder()).append("D").append(voBillInfo.getType()).toString()));
            if(voBillInfo.getCode() == null)
                voBillInfo.setCode(dmo.getBillCode(voBillInfo.getType(), voBillInfo.getID()));
            if(voBillInfo.getUI() == null)
            {
                String saTableInfo[] = SourceBillParaV3.getSourceInfo(voBillInfo.getType());
                if(saTableInfo != null)
                    voBillInfo.setUI(saTableInfo[8]);
                else
                    voBillInfo.setUI(dmo.getBillUI(voBillInfo.getType()));
            }
            LightBillVO forwards[] = voBillInfo.getForwardBillVOs();
            for(int i = 0; forwards != null && i < forwards.length; i++)
                findForwardBillsForBill(forwards[i]);

        }
        catch(Exception e)
        {
            throw new BusinessException(e);
        }
    }

    public void findSourceBillsForBill(LightBillVO voBillInfo)
        throws Exception
    {
        LightBillVO voaCurrentResult[] = voBillInfo.getSourceBillVOs();
        if(voaCurrentResult != null && voBillInfo.getDepth() != null && voaCurrentResult.length == voBillInfo.getDepth().intValue())
        {
            System.out.println((new StringBuilder()).append("Hint:Depth is OK.").append(voBillInfo.getDepth().intValue()).toString());
            return;
        }
        if(voBillInfo.getType().startsWith("A"))
        {
            System.out.println((new StringBuilder()).append("sssssss    =").append(voBillInfo.getType()).append(",").append(voBillInfo.getTypeName()).toString());
            findMMSourceBillsForBill(voBillInfo);
            return;
        }
        searchSourceBills(voBillInfo);
        DefaultSourceDMO dmo = new DefaultSourceDMO();
        voBillInfo.setTypeName(NCLangResOnserver.getInstance().getStrByID("billtype", (new StringBuilder()).append("D").append(voBillInfo.getType()).toString()));
        if(voBillInfo.getCode() == null)
            voBillInfo.setCode(dmo.getBillCode(voBillInfo.getType(), voBillInfo.getID()));
        if(voBillInfo.getUI() == null)
        {
            String saTableInfo[] = SourceBillParaV3.getSourceInfo(voBillInfo.getType());
            if(saTableInfo != null)
                voBillInfo.setUI(saTableInfo[8]);
            else
                voBillInfo.setUI(dmo.getBillUI(voBillInfo.getType()));
        }
        LightBillVO sources[] = voBillInfo.getSourceBillVOs();
        for(int i = 0; sources != null && i < sources.length; i++)
            findSourceBillsForBill(sources[i]);

    }

    private ISourceBillFinder getSourceBillFinder(String billType)
    {
        try
        {
        	if("7G".equals(billType))
        		return new DMMissionbillSourceDMO();
        	if("7D".equals(billType) || "7Y".equals(billType))
        		return new DMDeliverPlanSourceDMO();
        	if("7F".equals(billType) || "7X".equals(billType) || "7E".equals(billType))
        		return new DMDeliverbillSourceDMO();
        	if("7K".equals(billType))
        		return new DMTransInfoSourceDMO();
        	if("7J".equals(billType))
        		return new DMWayLostSourceDMO();
        	if("7W".equals(billType))
        		return new DMDelivFeeBillSourceDMO();
        	if("27".equals(billType))
        		return new SettleBillSourceDMO();
        	if("25".equals(billType))
        		return new InvoiceSourceDMO();
        	if("4T".equals(billType) || "45".equals(billType) || "47".equals(billType))
        		return new ICBillSourceDMO();
        	if("422X".equals(billType))
        		return new MRBillSourceDMO();
            return new DefaultSourceDMO();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }

    public String queryBillTempletID(String billType, String pk_corp, String userID)
        throws BusinessException
    {
        String templetID = null;
        try
        {
            DefaultSourceDMO dmo = new DefaultSourceDMO();
            templetID = dmo.getBillTempletID(billType, pk_corp, userID);
        }
        catch(Exception e)
        {
            throw new BusinessException(e);
        }
        return templetID;
    }

    public AggregatedValueObject queryBillVO(String id, String type)
        throws BusinessException
    {
        AggregatedValueObject vo = null;
        try
        {
            String info[] = SourceBillParaV3.getSourceInfo(type);
            if(info == null || info.length < 8)
                throw new RemoteException((new StringBuilder()).append(type).append(NCLangResOnserver.getInstance().getStrByID("scmpub", "UPPscmpub-001092")).toString());
            Class c = Class.forName(info[0]);
            Object ob = c.newInstance();
            Method m = c.getMethod(info[1], new Class[] {
                java.lang.String.class
            });
            vo = (AggregatedValueObject)m.invoke(ob, new Object[] {
                id
            });
        }
        catch(Exception e)
        {
            throw new BusinessException(e);
        }
        return vo;
    }

    public LightBillVO querySourceBillGraph(LightBillVO voBillInfo)
        throws BusinessException
    {
        LightBillVO voRet = null;
        try
        {
            voRet = new LightBillVO();
            voRet.setID(voBillInfo.getID());
            voRet.setType(voBillInfo.getType());
            voRet.setPk_corp(voBillInfo.getPk_corp());
            m_bMMUsed = false;
            try
            {
                CreatecorpDMO dmo = new CreatecorpDMO();
                if(voBillInfo.getPk_corp() != null)
                {
                    m_bMMUsed = dmo.isEnabled(voBillInfo.getPk_corp(), "MM");
                    System.out.println((new StringBuilder()).append("MM Starts ? ").append(m_bMMUsed).toString());
                } else
                {
                    System.out.println("pk_corp is null,so MM is not used.");
                }
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
            findSourceBillsForBill(voRet);
            findForwardBillsForBill(voRet);
        }
        catch(Exception e)
        {
            throw new BusinessException(e);
        }
        return voRet;
    }

    private void searchForwardBills(LightBillVO vo)
    {
        ArrayList alReturn;
        alReturn = SourceBillParaV3.getFwdBillTypes(vo.getType());
        if(alReturn == null || alReturn.size() == 0)
            return;
        try
        {
            String types[] = new String[alReturn.size()];
            alReturn.toArray(types);
            ISourceBillFinder ibf = getSourceBillFinder(vo.getType());
            for(int i = 0; i < types.length; i++)
            {
                System.out.println((new StringBuilder()).append("fwd===").append(types[i]).toString());
                if(types[i] != null && !types[i].startsWith("A"))
                {
                    LightBillVO tempVOs[] = ibf.getForwardBills(vo.getType(), vo.getID(), types[i]);
                    for(int j = 0; tempVOs != null && j < tempVOs.length; j++)
                        vo.addForwardBillVO(tempVOs[j]);

                } else
                {
                    nc.vo.mm.pub.pub1050.LightBillVO tempVOs[] = null;
                    if(isMMUsed())
                    {
                        SourceBillDMO mmDmo = new SourceBillDMO();
                        tempVOs = mmDmo.getForwardBills(vo.getType(), vo.getID(), null, types[i]);
                    } else
                    {
                        nc.bs.scm.mm.pub.pub1050.SourceBillDMO mmDmo = new nc.bs.scm.mm.pub.pub1050.SourceBillDMO();
                        tempVOs = mmDmo.getForwardBills(vo.getType(), vo.getID(), null, types[i]);
                    }
                    for(int j = 0; tempVOs != null && j < tempVOs.length; j++)
                        vo.addForwardBillVO(convertVOMM2SCM(tempVOs[j]));

                }
            }

        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return;
    }

    private void searchSourceBills(LightBillVO vo)
    {
        try
        {
            LightBillVO vos[] = getSourceBillFinder(vo.getType()).getSourceBills(vo.getType(), vo.getID());
            for(int i = 0; vos != null && i < vos.length; i++)
                vo.addSourceBillVO(vos[i]);

        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    private LightBillVO convertVOMM2SCM(nc.vo.mm.pub.pub1050.LightBillVO mmVO)
    {
        LightBillVO scmVO = new LightBillVO();
        scmVO.setBizType(mmVO.getBizType());
        scmVO.setCode(mmVO.getCode());
        scmVO.setID(mmVO.getID());
        scmVO.setType(mmVO.getType());
        scmVO.setTypeName(mmVO.getTypeName());
        scmVO.setUI(mmVO.getUI());
        nc.vo.mm.pub.pub1050.LightBillVO tempVOs[] = mmVO.getForwardBillVOs();
        if(tempVOs != null)
        {
            for(int i = 0; i < tempVOs.length; i++)
                scmVO.addForwardBillVO(convertVOMM2SCM(tempVOs[i]));

        }
        tempVOs = mmVO.getSourceBillVOs();
        if(tempVOs != null)
        {
            for(int i = 0; i < tempVOs.length; i++)
                scmVO.addSourceBillVO(convertVOMM2SCM(tempVOs[i]));

        }
        return scmVO;
    }

    private nc.vo.mm.pub.pub1050.LightBillVO getBasicMMVOFromScmVO(LightBillVO scmVO)
    {
        nc.vo.mm.pub.pub1050.LightBillVO mmVO = new nc.vo.mm.pub.pub1050.LightBillVO();
        mmVO.setBizType(scmVO.getBizType());
        mmVO.setCode(scmVO.getCode());
        mmVO.setID(scmVO.getID());
        mmVO.setType(scmVO.getType());
        mmVO.setTypeName(scmVO.getTypeName());
        mmVO.setUI(scmVO.getUI());
        mmVO.setSystemCode("MM");
        return mmVO;
    }

    private void copyScmVOFromMM(LightBillVO scmVO, nc.vo.mm.pub.pub1050.LightBillVO mmVO)
    {
        scmVO.setBizType(mmVO.getBizType());
        scmVO.setCode(mmVO.getCode());
        scmVO.setID(mmVO.getID());
        scmVO.setType(mmVO.getType());
        scmVO.setTypeName(mmVO.getTypeName());
        scmVO.setUI(mmVO.getUI());
    }

    private void findMMForwardBillsForBill(LightBillVO voBillInfo)
        throws BusinessException
    {
        try
        {
            nc.vo.mm.pub.pub1050.LightBillVO mmVO = getBasicMMVOFromScmVO(voBillInfo);
            nc.bs.scm.mm.pub.pub1050.SourceBillDMO dmoMM = new nc.bs.scm.mm.pub.pub1050.SourceBillDMO();
            mmVO.setTypeName(NCLangResOnserver.getInstance().getStrByID("billtype", (new StringBuilder()).append("D").append(voBillInfo.getType()).toString()));
            mmVO.setCode(dmoMM.getBillCode(mmVO.getType(), mmVO.getID()));
            System.out.println((new StringBuilder()).append("find mm f =").append(voBillInfo.getCode()).append(",type=").append(voBillInfo.getType()).append(",type name=").append(voBillInfo.getTypeName()).append(",ui=").append(voBillInfo.getUI()).append(",id=").append(voBillInfo.getID()).toString());
            if(isMMUsed())
            {
                MMHelper.getIMMSourceBill().findForwardBillsForBill(null, mmVO);
            } else
            {
                SourceBillBO boMM = new SourceBillBO();
                boMM.findForwardBillsForBill(null, mmVO);
            }
            LightBillVO newBill = convertVOMM2SCM(mmVO);
            copyScmVOFromMM(voBillInfo, mmVO);
            LightBillVO tempVOs[] = newBill.getForwardBillVOs();
            if(tempVOs != null)
            {
                for(int i = 0; i < tempVOs.length; i++)
                    voBillInfo.addForwardBillVO(tempVOs[i]);

            }
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
            throw new BusinessException(ex.getMessage());
        }
    }

    private void findMMSourceBillsForBill(LightBillVO voBillInfo)
        throws BusinessException
    {
        try
        {
            nc.vo.mm.pub.pub1050.LightBillVO mmVO = getBasicMMVOFromScmVO(voBillInfo);
            nc.bs.scm.mm.pub.pub1050.SourceBillDMO dmoMM = new nc.bs.scm.mm.pub.pub1050.SourceBillDMO();
            mmVO.setTypeName(NCLangResOnserver.getInstance().getStrByID("billtype", (new StringBuilder()).append("D").append(voBillInfo.getType()).toString()));
            mmVO.setCode(dmoMM.getBillCode(mmVO.getType(), mmVO.getID()));
            System.out.println((new StringBuilder()).append("find mm s =").append(voBillInfo.getCode()).append(",type=").append(voBillInfo.getType()).append(",type name=").append(voBillInfo.getTypeName()).append(",ui=").append(voBillInfo.getUI()).append(",id=").append(voBillInfo.getID()).toString());
            if(isMMUsed())
            {
                MMHelper.getIMMSourceBill().findSourceBillsForBill(null, mmVO);
            } else
            {
                SourceBillBO boMM = new SourceBillBO();
                mmVO = boMM.findSourceBillsForBill(null, mmVO);
            }
            LightBillVO newBill = convertVOMM2SCM(mmVO);
            copyScmVOFromMM(voBillInfo, mmVO);
            LightBillVO tempVOs[] = newBill.getSourceBillVOs();
            if(tempVOs != null)
            {
                for(int i = 0; i < tempVOs.length; i++)
                    voBillInfo.addSourceBillVO(tempVOs[i]);

            }
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
            throw new BusinessException(ex.getMessage());
        }
    }

    private boolean isMMUsed()
    {
        return m_bMMUsed;
    }

    public void setMMUsed(boolean bMMUsed)
    {
        m_bMMUsed = bMMUsed;
    }

    public String[] getSourceBillInfo(String sSourceBillType[], String sSourceBillHID[])
        throws BusinessException
    {
        if(sSourceBillType == null || sSourceBillType.length == 0)
            return null;
        if(sSourceBillHID == null || sSourceBillHID.length == 0)
            return null;
        if(sSourceBillType.length != sSourceBillHID.length)
        {
            System.out.println("\u6765\u6E90\u5355\u636E\u7C7B\u578B\u3001\u6765\u6E90\u5355\u636E\u5934ID\u7684\u6570\u7EC4\u4E2A\u6570\u4E0D\u76F8\u7B49\uFF01");
            return null;
        }
        int nCount = sSourceBillType.length;
        for(int i = 0; i < nCount; i++)
        {
            if(sSourceBillType[i] == null || sSourceBillType[i].trim().length() == 0)
            {
                System.out.println("\u6765\u6E90\u5355\u636E\u7C7B\u578B\u4E3A\u7A7A\uFF01");
                return null;
            }
            if(sSourceBillHID[i] == null || sSourceBillHID[i].trim().length() == 0)
            {
                System.out.println("\u6765\u6E90\u5355\u636E\u5934ID\u4E3A\u7A7A\uFF01");
                return null;
            }
        }

        Hashtable temp = new Hashtable();
        for(int i = 0; i < nCount; i++)
            if(!temp.containsKey(sSourceBillType[i]))
            {
                Vector v = new Vector();
                Vector v1 = new Vector();
                v1.addElement(sSourceBillHID[i]);
                v.addElement(v1);
                temp.put(sSourceBillType[i], v);
            } else
            {
                Vector v = (Vector)temp.get(sSourceBillType[i]);
                Vector v1 = (Vector)v.elementAt(0);
                v1.addElement(sSourceBillHID[i]);
                temp.put(sSourceBillType[i], v);
            }

        Hashtable hHead = new Hashtable();
        Enumeration keys = temp.keys();
        ScmPubImpl queryBo = new ScmPubImpl();
        Object oaRet[][] = (Object[][])null;
        do
        {
            if(!keys.hasMoreElements())
                break;
            Object key = keys.nextElement();
            Object o = ConstantVO.HASH_BILL_INFOS.get(key);
            if(o != null)
            {
                String info[] = (String[])(String[])o;
                Vector v = (Vector)temp.get(key);
                Vector v1 = (Vector)v.elementAt(0);
                Vector v11 = new Vector();
                for(int i = 0; i < v1.size(); i++)
                {
                    Object oTemp = v1.elementAt(i);
                    if(!v11.contains(oTemp))
                        v11.addElement(oTemp);
                }

                String sHID[] = new String[v11.size()];
                v11.copyInto(sHID);
                oaRet = queryBo.queryArrayValue(info[1], info[2], new String[] {
                    info[3]
                }, sHID);
                if(oaRet != null && oaRet.length == sHID.length)
                {
                    int i = 0;
                    while(i < sHID.length) 
                    {
                        if(sHID[i] != null && oaRet[i] != null && oaRet[i][0] != null)
                            hHead.put(sHID[i], oaRet[i][0].toString());
                        i++;
                    }
                }
            }
        } while(true);
        String saRet[] = new String[nCount];
        for(int i = 0; i < nCount; i++)
            if(sSourceBillHID[i] != null)
                saRet[i] = (String)hHead.get(sSourceBillHID[i]);

        return saRet;
    }

    public String[][] getSourceBillInfo(String sSourceBillType[], String sSourceBillHID[], String sSourceBillBID[])
        throws BusinessException
    {
        if(sSourceBillType == null || sSourceBillType.length == 0)
            return (String[][])null;
        if(sSourceBillHID == null || sSourceBillHID.length == 0)
            return (String[][])null;
        if(sSourceBillBID == null || sSourceBillBID.length == 0)
            return (String[][])null;
        if(sSourceBillType.length != sSourceBillHID.length || sSourceBillHID.length != sSourceBillBID.length)
        {
            System.out.println("\u6765\u6E90\u5355\u636E\u7C7B\u578B\u3001\u6765\u6E90\u5355\u636E\u5934ID\u3001\u6765\u6E90\u5355\u636E\u4F53ID\u7684\u6570\u7EC4\u4E2A\u6570\u4E0D\u76F8\u7B49\uFF01");
            return (String[][])null;
        }
        int nCount = sSourceBillType.length;
        for(int i = 0; i < nCount; i++)
        {
            if(sSourceBillType[i] == null || sSourceBillType[i].trim().length() == 0)
            {
                System.out.println("\u6765\u6E90\u5355\u636E\u7C7B\u578B\u4E3A\u7A7A\uFF01");
                return (String[][])null;
            }
            if(sSourceBillHID[i] == null || sSourceBillHID[i].trim().length() == 0)
            {
                System.out.println("\u6765\u6E90\u5355\u636E\u5934ID\u4E3A\u7A7A\uFF01");
                return (String[][])null;
            }
            if(sSourceBillBID[i] == null || sSourceBillBID[i].trim().length() == 0)
            {
                System.out.println("\u6765\u6E90\u5355\u636E\u4F53ID\u4E3A\u7A7A\uFF01");
                return (String[][])null;
            }
        }

        Hashtable temp = new Hashtable();
        for(int i = 0; i < nCount; i++)
            if(!temp.containsKey(sSourceBillType[i]))
            {
                Vector v = new Vector();
                Vector v1 = new Vector();
                Vector v2 = new Vector();
                v1.addElement(sSourceBillHID[i]);
                v2.addElement(sSourceBillBID[i]);
                v.addElement(v1);
                v.addElement(v2);
                temp.put(sSourceBillType[i], v);
            } else
            {
                Vector v = (Vector)temp.get(sSourceBillType[i]);
                Vector v1 = (Vector)v.elementAt(0);
                Vector v2 = (Vector)v.elementAt(1);
                v1.addElement(sSourceBillHID[i]);
                v2.addElement(sSourceBillBID[i]);
                temp.put(sSourceBillType[i], v);
            }

        Hashtable hHead = new Hashtable();
        Hashtable hBody = new Hashtable();
        Enumeration keys = temp.keys();
        Object oaRet[][] = (Object[][])null;
        ScmPubImpl queryBo = new ScmPubImpl();
        do
        {
            if(!keys.hasMoreElements())
                break;
            Object key = keys.nextElement();
            Object o = ConstantVO.HASH_BILL_INFOS.get(key);
            if(o != null)
            {
                String info[] = (String[])(String[])o;
                Vector v = (Vector)temp.get(key);
                Vector v1 = (Vector)v.elementAt(0);
                Vector v2 = (Vector)v.elementAt(1);
                Vector v11 = new Vector();
                for(int i = 0; i < v1.size(); i++)
                {
                    Object oTemp = v1.elementAt(i);
                    if(!v11.contains(oTemp))
                        v11.addElement(oTemp);
                }

                String sHID[] = new String[v11.size()];
                v11.copyInto(sHID);
                Vector v22 = new Vector();
                for(int i = 0; i < v2.size(); i++)
                {
                    Object oTemp = v2.elementAt(i);
                    if(!v22.contains(oTemp))
                        v22.addElement(oTemp);
                }

                String sBID[] = new String[v22.size()];
                v22.copyInto(sBID);
                oaRet = queryBo.queryArrayValue(info[1], info[2], new String[] {
                    info[3]
                }, sHID);
                if(oaRet != null && oaRet.length == sHID.length)
                {
                    for(int i = 0; i < sHID.length; i++)
                        if(sHID[i] != null && oaRet[i] != null && oaRet[i][0] != null)
                            hHead.put(sHID[i], oaRet[i][0].toString());

                    if(info[4] != null)
                    {
                        oaRet = queryBo.queryArrayValue(info[4], info[5], new String[] {
                            info[6]
                        }, sBID);
                        if(oaRet != null && oaRet.length == sBID.length)
                        {
                            int i = 0;
                            while(i < sBID.length) 
                            {
                                if(sBID[i] != null && oaRet[i] != null && oaRet[i][0] != null)
                                    hBody.put(sBID[i], oaRet[i][0].toString());
                                i++;
                            }
                        }
                    }
                }
            }
        } while(true);
        String saRet[][] = new String[nCount][2];
        for(int i = 0; i < nCount; i++)
        {
            saRet[i][0] = (String)hHead.get(sSourceBillHID[i]);
            saRet[i][1] = (String)hBody.get(sSourceBillBID[i]);
        }

        return saRet;
    }

    private boolean m_bMMUsed;
}
